package com.china08.yxyapi.api.manage.tec.teaching.scoreport.createexam;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.scoreport.Exam;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.scoreport.ExamRepository;
import com.china08.yxyapi.util.YxUserPointsUtilV3;

/**
 * 创建考试 保存
 * 
 */
@CrossOrigin
@RestController
public class CreateExamSaveController extends YxyApiBaseController {

    @Autowired
    private ExamRepository examRepository;
    @Autowired
    private YxUserPointsUtilV3  yxUserPointsUtilV3;
    @RequestMapping(value = "/api_yw/manage/tec/teaching/scoreport/createexam/sav", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
    	RespModel model = new RespModel();
    	String schoolId = getProfile(request, response).getSchoolId(); // 学校id
    	String userId = getProfile(request, response).getId();//当前登录用户id
    	List<Exam> exam1 = new ArrayList<Exam>();
    	if (reqModel.examId == null || reqModel.examId.equals("")) {
    		exam1 = examRepository.findByNameAndSchoolIdAndTeacherId(reqModel.name,schoolId,userId);
        	if (exam1.size()>0) {
    			Assert.isTrue(exam1.size()==0, "当前考试名称已存在,请重新输入!");
    			return model;
    		}
		}
    	boolean success = true;
    	try {
        String teacherId = getProfile(request, response).getId(); // 发布用户:ID
        String teacherNick = getProfile(request, response).getUserNick(); // 发布用户：name
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");// 设置日期格式
        String examId = df.format(new Date()).replace(" ", ""); // 考试编号
        String semester = "";
        semester = reqModel.semester;
        String id = null;
        List<ClassModel> classIdLst = new ArrayList<ClassModel>();
        classIdLst = reqModel.classId;
        Exam exam = null;
        List<BookContent> bookContents = reqModel.bookContents; // 章节
        List<ExamQues> questions = new ArrayList<ExamQues>();
        questions = reqModel.bigques; // 试题

        // 学段名称
        String phaseName = "";
        // 学科名称
        String subjectName = "";
        // 学科id
        String subjectId = "";
        if (reqModel.subject != null && !reqModel.subject.equals("")) {
            phaseName = reqModel.subject.split("-")[0];
            subjectName = reqModel.subject.split("-")[1];
            subjectId = reqModel.subject.split("-")[2];
        }
        // 版本id
        String versionId = "";
        // 版本name
        String versionName = "";
        if (reqModel.version != null && !reqModel.version.equals("")) {
            versionId = reqModel.version.split("-")[0];
            versionName = reqModel.version.split("-")[1];
        }
        List<String>  examIdList = new ArrayList<String>();
        for (ClassModel classId : classIdLst) {
            exam = new Exam();
            if (reqModel.examId == null || reqModel.examId.equals("")) {
            	id = examId + classId.classId; // id 考试编号+班级id
			}else{				
				id = reqModel.examId;
			}
            exam.setId(id == null ? "" : id);
            exam.setExamId(examId == null ? "" : examId);
            exam.setName(reqModel.name == null ? "" : reqModel.name);
            exam.setType(reqModel.type == null ? "" : reqModel.type);
            exam.setSchoolId(schoolId == null ? "" : schoolId);

            exam.setSubject(subjectId);
            exam.setSubjectName(subjectName);
            exam.setStage(phaseName);
            exam.setVersionName(versionName);
            exam.setVersion(versionId);
            exam.setSemester(semester.split("-")[0]);
            exam.setSemesterName(semester.split("-")[1]);
            Exam.BookContent bookConten = null;
            List<Exam.BookContent> bookContentList = new ArrayList<Exam.BookContent>();
            for (BookContent bookContent : bookContents) {
                bookConten = exam.new BookContent();
                bookConten.id = bookContent.id == null ? "" : bookContent.id;
                bookConten.pid = bookContent.pId == null ? "" : bookContent.pId;
                bookConten.name = bookContent.name == null ? "" : bookContent.name;
                bookContentList.add(bookConten);
            }
            exam.setBookContents(bookContentList);// 章节对象
            exam.setTotalScore(reqModel.totalScore == null ? 0 : reqModel.totalScore);// 考试总分
            
            if (reqModel.examDate!=null) {
            	Calendar c = Calendar.getInstance();  
                c.setTime(reqModel.examDate);  
                c.add(Calendar.DAY_OF_MONTH, 1);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String date = sdf.format(reqModel.examDate);
                exam.setExamDate(Integer.parseInt(date.substring(0, 10).replace("-", "")));// 考试时间
			}
            exam.setTeacherId(teacherId == null ? "" : teacherId);// 发布用户
            exam.setTeacherNick(teacherNick == null ? "" : teacherNick);// 发布用户名称
            Exam.ExamQues examQues1 = null;
            List<Exam.ExamQues> questionsList = new ArrayList<Exam.ExamQues>();
            Integer order_num = 0;

            Integer bigQuesId = 0;// 大题号id
            if (questions.size() > 0) {
                for (ExamQues examQues : questions) {
                    bigQuesId += 1;
                    if (examQues.small != null && examQues.small.size() > 0) {
                        Integer smallQuesId = 0;// 小题号id
                        for (Small small : examQues.small) {
                            examQues1 = exam.new ExamQues();
                            smallQuesId += 1;
                            examQues1.section = bigQuesId; // 大题号id
                            examQues1.no = smallQuesId; // 小题号id
                            examQues1.sectionName = examQues.name; // 大题名称
                            examQues1.noName = small.name; // 小题名称
                            order_num += 1; // 小题序列号+1
                            examQues1.order_num = order_num;
                            examQues1.score = small.point; // 小题分数
                            questionsList.add(examQues1);
                        }
                    } else {
                        order_num += 1; // 大题序列号+1
                        examQues1 = exam.new ExamQues();
                        examQues1.section = bigQuesId; // 大题号id
                        examQues1.sectionName = examQues.name; // 大题名称
                        examQues1.noName = "";// 小题名称
                        examQues1.no = 0;// 小题号id
                        examQues1.score = examQues.point;
                        examQues1.order_num = order_num;
                        questionsList.add(examQues1);
                    }

                }
            }
            

            exam.setQuestions(questionsList);// 试题
            exam.setStatus(reqModel.status == null ? 0 : reqModel.status); // 状态
                                                                           // 0--未录入数据
                                                                           // ,
                                                                           // 1--未发送,2--已发送
            exam.setClassId(classId.classId == null ? "" : classId.classId);// 班级id
            exam.setClassName(classId.className == null ? "" : classId.className);// 班级名称

            Exam.Stu stu = null;
            List<Exam.Stu> stusList = new ArrayList<Exam.Stu>();
            for (Student student : classId.studentCount) {
                stu = exam.new Stu();
                stu.student_id = student.id;
                stu.student_name = student.name;
                stu.student_no = student.studentNo;
                stu.grade_name = student.greadName;
                stu.gender = student.gender;
                stusList.add(stu);
            }
            exam.setStudents(stusList);
            
            Date currentTime = new Date();  
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            String dateString = formatter.format(currentTime);  
            
            
            exam.setCreatedDate(Timestamp.valueOf(dateString));
            examRepository.save(exam);// 将试卷实体类进行保存
            
            examIdList.add(id);
        }
        
        model.examIdList = examIdList;
    	} catch (Exception e) {
    		e.printStackTrace();
    		success = false;
		}
    	model.success  = success;
    	if (model.success) {
    	    yxUserPointsUtilV3.createExam(userId);
        }
        return model;
    }

    protected static class RespModel extends YxyApiRespModel {
    	//   
    	public List<String> examIdList;
    	//是否保存成功
    	public boolean success;
    }

    protected static class ReqModel extends YxyApiReqModel {
    	//考试id
    	public String examId;
        // 考试名称
        public String name;

        // 考试类型
        public String type;
        // 学科
        public String subject;

        // 学科名称
        // public String subjectName;

        // 版本名称
        // public String versionName;

        // 版本
        public String version;

        // 试卷考核章节
        public List<BookContent> bookContents;

        // 考试总分
        public Integer totalScore;

        // 考试时间
        public Date examDate;

        // 试题
        public List<ExamQues> bigques;

        // 状态 0--未录入数据 , 1--未发送,2--已发送
        public Integer status;

        // 班级id
        public List<ClassModel> classId;
        
        //策别
        public String semester;
        // 班级名称
        // public String className;

        // 学生list
        // public List<Student> students;
    }

    public static class ClassModel {
        // 班级id
        public String classId;
        // 班级name
        public String className;
        public List<Student> studentCount;

    }

    public static class ExamQues {
        public String name; // 大题名称
        public Integer point; // 分数
        public List<Small> small;// 小题集合
    }

    public static class Small {
        public String name;// 小题名称
        public Integer point;// 小题分数
    }

    public static class BookContent {
        public String pId;
        public String id;
        public String name;
    }

    public static class Student {
        // 学生id
        public String id;
        // 学生name
        public String name;
        // 学生学号
        public String studentNo;
        // 年级name
        public String greadName;
        // 性别
        public Integer gender;
        /*
         * // id public String id; // 姓名 public String name; // 年级ID public
         * String gradeId; // 年级name public String greadName; // 班级:ID public
         * String ownerClassId; // 班级name public String ownerClassNick; // 学号
         * public String studentNo;
         */
    }
}
